package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerHomeNewsComponent;
import com.kmproject.haifu.di.module.HomeNewsModule;
import com.kmproject.haifu.mvp.contract.HomeNewsContract;
import com.kmproject.haifu.mvp.model.entity.beans.HomeNewsBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsGetHomeNews;
import com.kmproject.haifu.mvp.presenter.HomeNewsPresenter;
import com.kmproject.haifu.mvp.ui.activity.HomeNewsDetailActivity;
import com.kmproject.haifu.mvp.ui.activity.WebViewActivity;
import com.kmproject.haifu.mvp.ui.adapter.HomeNewsAdapter;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 *
 */
public class HomeNewsFragment extends BaseFragment<HomeNewsPresenter> implements HomeNewsContract.View {
    @BindView(R.id.srl_home_news)
    PullToRefreshView srl_home_news;
    @BindView(R.id.rv_home_news)
    RecyclerView rv_home_news;
    @BindView(R.id.i_empty)
    View empty;
    private HomeNewsAdapter adapter;

    private ReqParamsGetHomeNews reqParamsGetHomeNews;

    private static final String TAB_FLAG = "tabFlag";
    private int tabFlag = 0;

    public static HomeNewsFragment newInstance(int tabFlag) {
        HomeNewsFragment fragment = new HomeNewsFragment();
        Bundle args = new Bundle();
        args.putInt(TAB_FLAG, tabFlag);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeNewsComponent
                .builder()
                .appComponent(appComponent)
                .homeNewsModule(new HomeNewsModule(this))//请将HomeNewsModule()第一个首字母改为小写
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_news, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if (getArguments() != null) {
            tabFlag = getArguments().getInt(TAB_FLAG, 0);
        }

        rv_home_news.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(true).build());
        ArmsUtils.configRecyclerView(rv_home_news, new LinearLayoutManager(getContext()));
        rv_home_news.setItemAnimator(new DefaultItemAnimator());
        srl_home_news.setEnableRefresh(true);
        srl_home_news.setEnableAutoLoadMore(false);
        srl_home_news.setEnableHeaderTranslationContent(true);

        adapter = new HomeNewsAdapter(new ArrayList<>(), getContext());
        rv_home_news.setAdapter(adapter);

        adapter.setOnItemClickListener((adapter, view, position) -> {
            HomeNewsBean homeNewsBean = (HomeNewsBean) adapter.getItem(position);
            Intent intent;
            if (Objects.requireNonNull(homeNewsBean).getIsAdvertisement() == 0) {//是否是广告:0-否，1-是
                intent = new Intent(getContext(), HomeNewsDetailActivity.class);
                intent.putExtra("homeNewsBean", homeNewsBean);
                ArmsUtils.startActivity(intent);
            } else {
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "海服头条");
                intent.putExtra("url", homeNewsBean.getLink());
//                intent.putExtra("url", "https://www.baidu.com/");
                ArmsUtils.startActivity(intent);
            }
        });

        srl_home_news.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 加载更多
                reqParamsGetHomeNews.setPage(curPageNo);
                getBisData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                // 刷新
                reqParamsGetHomeNews.setPage(curPageNo);
                getBisData();
            }
        });

        reqParamsGetHomeNews = new ReqParamsGetHomeNews();
        reqParamsGetHomeNews.setPage(1);
        reqParamsGetHomeNews.setLimit(AppConstant.pageSize);
        getBisData();
    }

    private void getBisData() {
        if (tabFlag == 1) {//要展示的类型:0-最新,1-最热
            // 请求最热资讯
            reqParamsGetHomeNews.setViewType(0);
            mPresenter.getHomeNews(reqParamsGetHomeNews);
        } else {
            // 请求推荐资讯
            reqParamsGetHomeNews.setViewType(1);
            mPresenter.getHomeNews(reqParamsGetHomeNews);
        }
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {
    }


    @Override
    public void showLoading() {
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
    }

    @Override
    public void getHomeNewsSuccess(List<HomeNewsBean> newsBeans) {
        srl_home_news.finishLoadMore();
        srl_home_news.finishRefresh();
        if (newsBeans != null && !newsBeans.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_home_news, true);
            if (ViewExtensionKt.isPullDown(srl_home_news, newsBeans.size(), reqParamsGetHomeNews.getLimit())) {
                adapter.setNewData(newsBeans);
            } else {
                adapter.addData(newsBeans);
            }
        } else {
            if (reqParamsGetHomeNews.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_home_news, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_home_news, false);
            }
        }
    }

    @Override
    public void getHomeNewsFailed() {
        srl_home_news.finishLoadMore();
        srl_home_news.finishRefresh();
        if (reqParamsGetHomeNews.getPage() > 1) {
            reqParamsGetHomeNews.setPage(reqParamsGetHomeNews.getPage() - 1);
        }
    }
}